package com.lagou.server.handler;

import com.lagou.server.ApplicationContextUtil;
import com.lagou.util.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException {

        RpcRequest request = (RpcRequest) msg;

        Class clazz = Class.forName(request.getClassName());
        Method method = clazz.getDeclaredMethod(request.getMethodName(), request.getParameterTypes());
        Object clazzObject = ApplicationContextUtil.getBean(clazz);
        Object result = method.invoke(clazzObject, request.getParameters());

        context.writeAndFlush(request.getRequestId() + ": " + result);
    }
}
